package com.tinyideatech.wechat.Interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tinyideatech.system.entity.CarDevice;
import com.tinyideatech.system.entity.MallMember;
import com.tinyideatech.system.service.ICarDeviceService;
import com.tinyideatech.system.service.IMallMemberService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by zhangy-5 on 2017/5/14.
 */
@Component
public class AppInterceptor extends HandlerInterceptorAdapter {

    @Value("${tinyideatech.host}")
    private String host;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private IMallMemberService memberService;

    @Autowired
    private ICarDeviceService deviceService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        HttpSession session = request.getSession();
//        String url = request.getRequestURL().toString();

        String deviceId = request.getParameter("deviceId");
        String url = host + "/wx/index?deviceId=" + deviceId;
        Long userId = (Long) session.getAttribute("user_id");
        if (userId == null) {
            String agent = request.getHeader("User-Agent");
            if (agent != null && agent.toLowerCase().indexOf("micromessenger") >= 0) {
                String code = request.getParameter("code");
                String state = request.getParameter("state");

                if (code != null && state != null && state.equals("1")) {
                    WxMpOAuth2AccessToken accessToken;
                    try {
                        accessToken = wxMpService.oauth2getAccessToken(code);
                        List<MallMember> memberList = memberService.list(new QueryWrapper<MallMember>().eq("open_id", accessToken.getOpenId()));
                        MallMember member;
                        if (memberList.size() == 0) {
//                            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(accessToken.getOpenId(), null);
//                            wxMpService.oauth2refreshAccessToken(accessToken.getRefreshToken());
                            WxMpUser wxMpUser = new WxMpUser();
                            wxMpUser.setOpenId(accessToken.getOpenId());
                            wxMpUser.setHeadImgUrl("/img/user.png");
                            wxMpUser.setNickname("会员");
                            List<CarDevice> deviceList = deviceService.list(new QueryWrapper<CarDevice>().eq("device_id", deviceId));
                            member = memberService.saveWxUser(wxMpUser, new MallMember(), deviceId);
                            if (deviceList.size() == 1) {
                                CarDevice device = deviceList.get(0);
                                if (device != null) {
                                    device.setMemberId(member.getMemberId());
                                    deviceService.updateById(device);
                                }
                            }
                        } else {
                            member = memberList.get(0);
                        }
                        session.setAttribute("device_id", deviceId);
                        session.setAttribute("user_id", member.getMemberId());
                        session.setAttribute("user_info", member);
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                    }
                } else {
                    String OAuth2Url = wxMpService.oauth2buildAuthorizationUrl(url, "snsapi_base", "1");
                    response.sendRedirect(OAuth2Url);
                    return false;
                }
            } else {
                response.sendRedirect(request.getContextPath() + "/start");
                return false;
            }
        }

        return true;
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void afterConcurrentHandlingStarted(
            HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    }

}
